import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';

import { AuthService } from './authService';

import { AppSettings } from '../app.settings';

@Injectable()
export class AuthGuard implements CanActivate {


  list:any;

  constructor(private authService:AuthService,private appSettings:AppSettings) {

    this.list = appSettings.getRoleNavList();
  }

  canActivate(route,state): Promise<boolean>  {

    // console.log("can active");


    // console.log(route);


    // console.log(state);

    //
    let url = state.url;



    return new Promise((resolve) => {
      this.authService.isLogin().then((user:any)=>{

        let role = user.activeVersionInfo.version;


        // routeList
        let routeList = this.list;

        if(routeList.length == 0){
          
          // 设置类目
          this.appSettings.roleNavInit(user);
          routeList = this.appSettings.getRoleNavList();
        }

        

        let boolean = false;


        // 查找是否在范围内
        for(let i in routeList){
          // console.log("");
          // console.log(url);
          // console.log('');
          // console.log(routeList[i].path);


          // console.log(":"+url.match(routeList[i].path));

          // 能在角色路由列表中找到
          if(url.match(routeList[i].path)){

            boolean = true;

            break;
          }
        }

        //是否在范围内-boolean
        //设置页面
        if(url == '/setting'){

          resolve(true);
        }
        if(boolean){

          resolve(true);

        }else{
          // 路由权限不足
          resolve(false);

          console.log(routeList);

          console.log(url+'路由权限不足');
        }



      },()=>{
        resolve(false);
      });
    });

  }
}
